// main
package main

import (
	"database/sql"
	"fmt"
	"go-redis/lib"
	"os"

	"time"

	_ "github.com/denisenkom/go-mssqldb"
	"github.com/garyburd/redigo/redis"
	_ "github.com/go-sql-driver/mysql"
	"gopkg.in/urfave/cli.v2"
)

func CreateRedisPool(redisURL string) *redis.Pool {
	return &redis.Pool{
		MaxIdle:     10,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.DialURL(redisURL)
			if err != nil {
				return nil, err
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			if err != nil {
				return fmt.Errorf("ping redis error: %s", err)
			}
			return nil
		},
	}
}

func run(c *cli.Context) error {
	db, err := sql.Open(c.String("db-type"), c.String("db-server"))
	db.SetConnMaxLifetime(30 * time.Second)
	// 数据库最多空闲数
	db.SetMaxIdleConns(20)
	// 数据库最大连接数
	db.SetMaxOpenConns(10)
	if err != nil {
		fmt.Println("connect datebaseServer faild,error message:", err)
		return err
	}
	defer db.Close()
	if err = db.Ping(); err != nil {
		fmt.Println("ping datebaseServer faild,error message:", err)
		return err
	}
	redis := CreateRedisPool(c.String("redis"))
	core := &lib.Core{DB: db, RedisPool: redis, Limit: c.Int("limit")}
	//c.RunCreateData(20, 50000)
	startTime := time.Now().Unix()
	core.Run()
	endTime := time.Now().Unix()
	fmt.Printf("%d 条数据，总共执行了 %d 秒", core.Count, endTime-startTime)
	return nil
}

func main() {
	app := &cli.App{
		Name:    "go-redis",
		Usage:   "go-redis",
		Version: "0.0.1",
		Action:  run,
		Flags: []cli.Flag{
			&cli.StringFlag{
				Name:  "db-type",
				Usage: "mysql or sqlserver",
				Value: "sqlserver",
			},
			&cli.StringFlag{
				Name:  "db-server",
				Usage: "user:password@tcp(host:port)/database",
				Value: "root:root@tcp(127.0.0.1:3306)/test",
			},
			&cli.StringFlag{
				Name:  "redis",
				Usage: "redis://:password@host:port",
				Value: "redis://127.0.0.1:6379",
			},
			&cli.StringFlag{
				Name:  "limit",
				Usage: "每次执行条数，int",
				Value: "5000",
			},
		},
	}
	app.Run(os.Args)
}
